#!/usr/bin/env bash

# 推荐组合（可根据需要更新）
REQ_FLUTTER="3.24.0"
REQ_AGP="8.5.0"
REQ_GRADLE="8.7"
REQ_KOTLIN="2.0.21"
REQ_JDK="17"

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

check_version() {
  local name=$1 current=$2 required=$3
  if [[ "$current" == "$required" ]]; then
    echo -e "✅ $name: $current"
  else
    echo -e "⚠️  $name: $current (推荐: $required)"
  fi
}

echo "=== 构建环境检查 ==="

# Flutter 版本
FLUTTER_VER=$(flutter --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -n 1)
check_version "Flutter" "$FLUTTER_VER" "$REQ_FLUTTER"

# Gradle 版本（来自 gradle-wrapper.properties）
if [ -f "android/gradle/wrapper/gradle-wrapper.properties" ]; then
  GRADLE_VER=$(grep distributionUrl android/gradle/wrapper/gradle-wrapper.properties | grep -oE '[0-9]+\.[0-9]+(\.[0-9]+)?' )
  check_version "Gradle Wrapper" "$GRADLE_VER" "$REQ_GRADLE"
else
  echo -e "${RED}未找到 gradle-wrapper.properties${NC}"
fi

# JDK 版本
JDK_VER=$(javac -version 2>&1 | awk '{print $2}' | cut -d'.' -f1)
check_version "JDK" "$JDK_VER" "$REQ_JDK"

# 解析 AGP & Kotlin 插件版本（Kotlin DSL 格式）
SETTINGS_FILE="android/settings.gradle.kts"
if [ -f "$SETTINGS_FILE" ]; then
  AGP_VER=$(grep -oE 'id\("com.android.application"\) version "[0-9]+\.[0-9]+\.[0-9]+"' "$SETTINGS_FILE" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')
  KOTLIN_VER=$(grep -oE 'id\("org.jetbrains.kotlin.android"\) version "[0-9]+\.[0-9]+\.[0-9]+"' "$SETTINGS_FILE" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')

  check_version "Android Gradle Plugin (AGP)" "$AGP_VER" "$REQ_AGP"
  check_version "Kotlin Gradle Plugin" "$KOTLIN_VER" "$REQ_KOTLIN"
else
  echo -e "${RED}未找到 $SETTINGS_FILE${NC}"
fi

echo "=== 检查完成 ==="
